package com.camerareader.mvp.login_page;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.camerareader.App;
import com.camerareader.BuildConfig;
import com.camerareader.R;
import com.camerareader.mvp.BaseActivity;
import com.camerareader.mvp.main_page.MainActivity;
import com.camerareader.util.SharedPreferencesUtil;
import com.fileoperation.CommonUtils;
import com.fileoperation.user.UserInfo;
import com.fileoperation.user.UserInfoParser;
import com.jakewharton.rxbinding.view.RxView;
import com.nettools.Constants;
import com.nettools.NetUtils;
import com.yzq.zxinglibrary.android.Intents;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;

public class LoginActivity extends AppCompatActivity {

    private EditText userName;
    private EditText password;
    CheckBox savePwd;
    private ProgressBar loading;
    private View logIn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().getDecorView().setBackgroundResource(R.drawable.loin_bg);
        initView();
    }

    private void initView() {
        userName = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        savePwd = findViewById(R.id.savePwd);
        loading = (ProgressBar) findViewById(R.id.login_loading);
        String lastAct = SharedPreferencesUtil.get("lastAct","");
        userName.setText(lastAct);
        String lastPwd = SharedPreferencesUtil.get("lastPwd","");
        if(lastPwd.length() > 0){
            savePwd.setChecked(true);
            password.setText(lastPwd);
        }
        if(BuildConfig.DEBUG){
            userName.setText("13651914460");
            password.setText("123123");
        }
        logIn = findViewById(R.id.log_in);
        RxView.clicks(logIn).throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
//                        JSONObject json = new JSONObject();
//                        JSONObject data = new JSONObject();
//                        try {
//                            data.put(UserInfo.ACCESS_TOKEN,"123123");
//                            data.put(UserInfo.REFRESH_TOKEN,"123123");
//                            JSONObject user = new JSONObject();
//                            user.put(UserInfo.UUID,"smss");
//                            user.put(UserInfo.USER_NAME,"ddsafasf");
//                            data.put("user",user);
//                            json.put(Constants.DATA,data);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                        UserInfoParser.parseUserInfo(json.optJSONObject(Constants.DATA), App.getApp());
//                        MainActivity.navigateMainActivity(LoginActivity.this);
//                        finish();

                        final String user = userName.getText().toString();
                        if (user.isEmpty()){
                            Toast.makeText(LoginActivity.this, "用户名不能为空！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        final String pwd = password.getText().toString();
                        if (pwd.isEmpty()){
                            Toast.makeText(LoginActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        loading.setVisibility(View.VISIBLE);

                        Observable.create(new Observable.OnSubscribe<JSONObject>() {
                            @Override
                            public void call(Subscriber<? super JSONObject> subscriber) {
                                try {
                                    Response response = NetUtils.getInstance().logIn(user, pwd);
                                    JSONObject json = new JSONObject(response.body().string());
                                    System.out.println(json.toString());
                                    if (json.optBoolean(Constants.STATUS)){
                                        UserInfoParser.parseUserInfo(json.optJSONObject(Constants.DATA), App.getApp());
                                        subscriber.onNext(json);
                                    }else {
                                        subscriber.onError(new Exception(json.optString(Constants.MSG)));
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                subscriber.unsubscribe();
                            }
                        }).subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<JSONObject>() {
                                    @Override
                                    public void onCompleted() {
                                        loading.setVisibility(View.GONE);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                        loading.setVisibility(View.GONE);

                                    }

                                    @Override
                                    public void onNext(JSONObject jsonObject) {
                                        SharedPreferencesUtil.put("lastAct",userName.getText().toString());
                                        if(savePwd.isChecked()){
                                            SharedPreferencesUtil.put("lastPwd",password.getText().toString());
                                        }
                                        if (UserInfo.getInstance().isLogin()){
                                            MainActivity.navigateMainActivity(LoginActivity.this);
                                            finish();
                                        }else {
                                            Toast.makeText(LoginActivity.this, "登录失败！", Toast.LENGTH_SHORT).show();
                                        }
                                        loading.setVisibility(View.GONE);
                                    }
                                });
                    }
                });



    }



    public static void navigateLoginActivity(Activity activity){
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        activity.startActivity(intent);
    }
}
